package com.licheedev.rxhttpdemo

import android.Manifest
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.licheedev.myutils.LogPlus
import com.licheedev.rxhttpdemo.bean.BaseBean
import com.licheedev.rxhttpdemo.bean.HomeBean
import com.licheedev.rxhttpextdemo.R
import kotlinx.android.synthetic.main.activity_main.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asRawBean
import rxhttpext.httpErrorMsg
import rxhttpext.observeOnMain
import java.io.File

@RuntimePermissions
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        button.setOnClickListener {

            val macnoParam = mapOf("macno" to "0000000003602")

            RxHttp.postForm("apk_index")
                .addAll(macnoParam) // 可以添加一个Map作为请求参数
                //.add("time", System.currentTimeMillis()) // 单请求参数
                //.apply {
                //    // 带条件的请求参数
                //    add("key", if (it == null) "0" else "1")
                //}
                .asBean01(HomeBean::class.java)
                .observeOnMain()
                .doFinally {
                    LogPlus.i("finished")
                }
                .subscribe({
                    LogPlus.i("success=${it}")
                }, {
                    LogPlus.e(it.httpErrorMsg)
                })
        }

        btnUpload.setOnClickListener {

            uploadFileWithPermissionCheck()

        }


        Glide.with(this)
            .load("https://image1.suning.cn/uimg/cms/img/159642507148437980.png")
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(image)

    }

    @NeedsPermission(
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun uploadFile() {
        
        val dir = getExternalFilesDir("upload")
        dir?.mkdirs()
        val file = File(dir, "test_short_video.mp4")
        RxHttp.postForm("https://xxxxxx.xxxxxx.cn/user_api/upload")
            .addFile("file", file)
            .asRawBean<BaseBean>()
            .subscribe({
                LogPlus.e(it.toString())
            }, {
                LogPlus.e("error", it)
            })
    }

    //@OnPermissionDenied(
    //    Manifest.permission.WRITE_EXTERNAL_STORAGE
    //)
    fun onExternalStorageDenied() {
        // todo
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }
}